package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisConstant;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SettleAccountErrorCodeEnum;
import com.xbongbong.pro.product.pojo.dto.CostRecalculationDTO;
import com.xbongbong.pro.product.pojo.dto.SettleAccountsDTO;
import com.xbongbong.pro.product.pojo.dto.SettleAccountsListDTO;
import com.xbongbong.pro.product.pojo.vo.SettleAccountsListVO;
import com.xbongbong.pro.product.pojo.vo.SettleAccountsVO;
import com.xbongbong.pro.rabbitmq.producer.CostRecalculationProducer;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.BatchFlowBillEntity;
import com.xbongbong.saas.domain.entity.ProductWarehouseEntity;
import com.xbongbong.saas.domain.entity.SettleAccountsEntity;
import com.xbongbong.saas.domain.entity.StockFlowBillEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.StockTypeEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.model.BatchFlowBillModel;
import com.xbongbong.saas.model.CostAdjustProductModel;
import com.xbongbong.saas.model.InstockProductModel;
import com.xbongbong.saas.model.OutstockProductModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductStockModel;
import com.xbongbong.saas.model.ProductWarehouseModel;
import com.xbongbong.saas.model.SettleAccountsModel;
import com.xbongbong.saas.model.StockFlowBillModel;
import com.xbongbong.saas.model.WarehouseOristockProductModel;
import com.xbongbong.saas.service.SettleAccountsService;
import com.xbongbong.sys.domain.entity.FeeCompanyEntity;
import com.xbongbong.sys.model.FeeCompanyModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author WuHB
 * @date 2021/11/22 08:54
 */
@Service("settleAccountsService")
public class SettleAccountsServiceImpl implements SettleAccountsService {
    private static final Logger LOG = LoggerFactory.getLogger(SettleAccountsServiceImpl.class);

    @Resource
    private SettleAccountsModel settleAccountsModel;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private FeeCompanyModel feeCompanyModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private StockFlowBillModel stockFlowBillModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private BatchFlowBillModel batchFlowBillModel;
    @Resource
    private InstockProductModel instockProductModel;
    @Resource
    private OutstockProductModel outstockProductModel;
    @Resource
    private ProductWarehouseModel productWarehouseModel;
    @Resource
    private ProductStockModel productStockModel;
    @Resource
    private CostAdjustProductModel costAdjustProductModel;
    @Resource
    private WarehouseOristockProductModel warehouseOristockProductModel;
    @Resource
    private CostRecalculationProducer costRecalculationProducer;

    /**
     * 获取上一次结账日期，系统启用日期
     *
     * @param baseDTO
     * @throws XbbException 业务异常
     * @author ruansicheng
     * @date 2021/11/19 2:13
     */
    @Override
    public SettleAccountsVO getCheckDate(BaseDTO baseDTO) throws XbbException {
        SettleAccountsVO settleAccountsVO = new SettleAccountsVO();
        String corpid = baseDTO.getCorpid();
        //获取系统启用日期
        FeeCompanyEntity feeCompanyEntity = feeCompanyModel.getFirstFeeCompanyIgnoreIsPay(corpid);
        if (feeCompanyEntity == null) {
            throw new XbbException(SettleAccountErrorCodeEnum.API_ERROR_254009);
        }
        //获取上一次结账日期
        Long lastCheckOutDate;
        SettleAccountsEntity lastSettleAccounts = settleAccountsModel.getLastSettleAccounts(corpid);
        if (Objects.nonNull(lastSettleAccounts)) {
            lastCheckOutDate = lastSettleAccounts.getCheckOutTime();
        } else {
            //如果没有上一次结账，是第一次结账，则需要重算系统启用日期到当前结账日起数据
            lastCheckOutDate = null;
        }
        settleAccountsVO.setLastCheckOutDate(lastCheckOutDate);
        settleAccountsVO.setStartTime(feeCompanyEntity.getStartTime());
        return settleAccountsVO;
    }

    /**
     * 新增结账
     *
     * @param settleAccountsDTO
     * @throws XbbException 业务异常
     * @author ruansicheng
     * @date 2021/11/19 2:13
     */
    @Override
    @Transactional
    public SettleAccountsVO addSettleAccounts(SettleAccountsDTO settleAccountsDTO) throws XbbException {
        SettleAccountsVO settleAccountsVO = new SettleAccountsVO();
        String corpid = settleAccountsDTO.getCorpid();
        //结账中校验，在结账中操作结账
        String redisHelperValue = paasRedisHelper.getValue(RedisPrefixConstant.SETTLE_ACCOUNTS, corpid);
        if (StringUtil.isNotEmpty(redisHelperValue)) {
            throw new XbbException(SettleAccountErrorCodeEnum.API_ERROR_254007);
        }
        //获取系统启用日期
        FeeCompanyEntity feeCompanyEntity = feeCompanyModel.getFirstFeeCompanyIgnoreIsPay(corpid);
        if (Objects.isNull(feeCompanyEntity) || Objects.isNull(feeCompanyEntity.getStartTime())) {
            throw new XbbException(SettleAccountErrorCodeEnum.API_ERROR_254009);
        }
        Long checkOutDate = settleAccountsDTO.getDate();
        //校验结账日期不能小于系统启用日期
        if (checkOutDate < feeCompanyEntity.getStartTime()) {
            throw new XbbException(SettleAccountErrorCodeEnum.API_ERROR_254006);
        }
        //获取上一次结账日期
        Long lastCheckOutDate;
        SettleAccountsEntity lastSettleAccounts = settleAccountsModel.getLastSettleAccounts(corpid);
        if (Objects.nonNull(lastSettleAccounts)) {
            lastCheckOutDate = lastSettleAccounts.getCheckOutTime();
        } else {
            //如果没有上一次结账，是第一次结账，则需要重算系统启用日期到当前结账日起数据
            lastCheckOutDate = feeCompanyEntity.getStartTime();
        }
        //校验日期
        if (Objects.nonNull(lastCheckOutDate)){
            if (checkOutDate <= DateTimeUtil.getTodayEndInt(lastCheckOutDate)) {
                throw new XbbException(SettleAccountErrorCodeEnum.API_ERROR_254005);
            }
        }
        // 本地调试用-清除限制次数缓存
        //paasRedisHelper.removeValue(RedisPrefixConstant.SETTLE_ACCOUNTS_TIMES, corpid);
        JSONObject jsonObject = JsonHelperUtil.parseObject(paasRedisHelper.getValue(RedisPrefixConstant.SETTLE_ACCOUNTS_TIMES, corpid));
        Long endTime = DateTimeUtil.getTodayEndInt(DateTimeUtil.getTodayInt());
        if (jsonObject.isEmpty()) {
            jsonObject.put(BusinessConstant.NUMBER_OF_TIMES, BasicConstant.ONE);
            jsonObject.put(BusinessConstant.TIME_LIMIT, endTime);
        } else {
            Integer times = jsonObject.getInteger(BusinessConstant.NUMBER_OF_TIMES);
            Long limitTime = jsonObject.getLong(BusinessConstant.TIME_LIMIT);
            Long now = DateTimeUtil.getInt();
            if (limitTime >= now) {
                if (times > BasicConstant.FOUR) {
                    throw new XbbException(SettleAccountErrorCodeEnum.API_ERROR_254002);
                } else {
                    jsonObject.put(BusinessConstant.NUMBER_OF_TIMES, times + BasicConstant.ONE);
                }
            } else {
                jsonObject.put(BusinessConstant.NUMBER_OF_TIMES, BasicConstant.ONE);
                jsonObject.put(BusinessConstant.TIME_LIMIT, endTime);
            }
        }
        //插入结账次数缓存
        paasRedisHelper.setValue(RedisPrefixConstant.SETTLE_ACCOUNTS_TIMES, corpid, jsonObject, RedisConstant.LONG_DURATION);
        String checkOutUserId = settleAccountsDTO.getUserId();
        String checkOutUserName = settleAccountsDTO.getLoginUserName();
        //设置结账中缓存
        paasRedisHelper.setValue(RedisPrefixConstant.SETTLE_ACCOUNTS, corpid, checkOutDate.toString(), RedisConstant.TINY_DURATION);
        //初始化结账实体
        SettleAccountsEntity settleAccountsEntity = new SettleAccountsEntity(corpid, lastCheckOutDate,
                checkOutDate, checkOutUserId, checkOutUserName, BasicConstant.ZERO, BasicConstant.ZERO);
        //插入结账数据
        Integer flag = settleAccountsModel.insert(settleAccountsEntity);
        if (flag < 1) {
            //失败时清除结账中缓存
            paasRedisHelper.removeValue(RedisPrefixConstant.SETTLE_ACCOUNTS, corpid);
            Integer times = jsonObject.getInteger(BusinessConstant.NUMBER_OF_TIMES);
            jsonObject.put(BusinessConstant.NUMBER_OF_TIMES, times - BasicConstant.ONE);
            paasRedisHelper.setValue(RedisPrefixConstant.SETTLE_ACCOUNTS_TIMES, corpid, jsonObject, RedisConstant.LONG_DURATION);
            throw new XbbException(SettleAccountErrorCodeEnum.API_ERROR_254001);
        }
        //进行结账重算
        recalculateProductCost(settleAccountsEntity);
        //设置返回
        settleAccountsVO.setDataId(settleAccountsEntity.getId());
        //清除结账中缓存
        paasRedisHelper.removeValue(RedisPrefixConstant.SETTLE_ACCOUNTS, corpid);
        //记录操作日志
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_SETTLE_ACCOUNTS), settleAccountsEntity.getCheckOutUserName());
        mongoLogHelp.buildLog4InfoArrWithoutAsync(null, corpid, settleAccountsEntity.getCheckOutUserId(), settleAccountsEntity.getCheckOutUserName(), OperateModuleTypeEnum.SETTLE_ACCOUNTS, OperateTypeEnum.NEW,
                "", "", memo, "");
        return settleAccountsVO;
    }

    /**
     * 结账重算方法
     *
     * @param settleAccountsEntity
     * @throws XbbException 业务异常
     * @author ruansicheng
     * @date 2021/11/19 2:13
     */
    private void recalculateProductCost(SettleAccountsEntity settleAccountsEntity) throws XbbException {
        String corpid = settleAccountsEntity.getCorpid();
        //结账日期
        Long checkOutDate = settleAccountsEntity.getCheckOutTime();
        //结账日期处理到结账日期当天的 23：59：59结束
        Long checkOutDateEnd = DateTimeUtil.getTodayEndInt(checkOutDate);
        //获取上一次结账日期
        Long lastCheckOutdate = settleAccountsEntity.getLastCheckOutTime();
        //获取上一次结账日期处理到第二天00：00：00开始, lastCheckOutdateStart = 23:59:59
        Long lastCheckOutdateStart = DateTimeUtil.getTodayEndInt(lastCheckOutdate);
        Long idGte = 0L;
        while (true) {
            //分页获取产品信息
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put(StringConstant.CORPID, corpid);
            params.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            params.put("dataParentIdGte", 0L);
            params.put("idGte", idGte);
            params.put("pageSize", 1000);
            params.put("orderByStr", "id asc");
            List<ProductEntityExt> productEntityExtList = productModel.findEntitys(params);
            if (productEntityExtList.isEmpty()) {
                break;
            }
            //每次查询出来最大的产品ID
            idGte = productEntityExtList.get(productEntityExtList.size() - 1).getId();
            //组装产品ID集合
            List<Long> productIdList = new ArrayList<>();
            productEntityExtList.forEach(item -> productIdList.add(item.getId()));
            //获取结帐日期之间的流水数据，批次流水---在产品集合范围内的
            params.clear();
            params.put(ParameterConstant.CORPID, corpid);
            params.put("greaterThanDate", lastCheckOutdateStart);
            params.put("lessEqualThanDate", checkOutDateEnd);
            params.put("productIdIn", productIdList);
            String sortStr = "date ASC";
            params.put("orderByStr", sortStr);
            params.put("del", DelEnum.NORMAL.getDel());
            List<StockFlowBillEntity> stockFlowBillEntities = stockFlowBillModel.findEntitys(params);
            List<BatchFlowBillEntity> batchFlowBillEntities = batchFlowBillModel.findEntitys(params);
            if (!stockFlowBillEntities.isEmpty()) {
                //库存流水数据根据产品ID分组
                Map<Long, List<StockFlowBillEntity>> stockFlowBillGroups = stockFlowBillEntities.stream().collect(Collectors.groupingBy(StockFlowBillEntity::getProductId));
                //获取期间产品ID列表
                List<Long>  productIds = stockFlowBillEntities.stream().map(StockFlowBillEntity::getProductId).distinct().collect(Collectors.toList());
                //获取产品数据
                Map<Long, ProductEntityExt> productEntityMap = productModel.getProductMapByIdIn(corpid, productIds, DelEnum.NORMAL.getDel());
                //获取分仓产品，和批次产品数据
                List<ProductWarehouseEntity> productWarehouseEntities = productWarehouseModel.getIdList(corpid, productIds);
                //根据产品ID分组
                Map<Long, List<ProductWarehouseEntity>> productWarehouseGroups = productWarehouseEntities.stream().collect(Collectors.groupingBy(ProductWarehouseEntity::getProductId));
            /*//根据产品ID分组
            List<ProductStockEntity> productStockEntities = productStockModel.listByProductIdIn(corpid, productIds);
            Map<Long, List<ProductStockEntity>> productStockGroups = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (!productStockEntities.isEmpty()) {
                productStockGroups = productStockEntities.stream().collect(Collectors.groupingBy(ProductStockEntity::getProductId));
            }*/
                //循环每个产品处理数据
                //重算参数
                JSONArray jsonArray = new JSONArray();
                JSONObject data = new JSONObject();
                for (Long productId : productEntityMap.keySet()) {
                    //获取该产品所有相关数据
                    List<StockFlowBillEntity> stockFlowBillEntityList = stockFlowBillGroups.get(productId);
                    List<BatchFlowBillEntity> batchFlowBillEntityList = batchFlowBillEntities.stream().filter(batchFlowBillEntity -> Objects.equals(productId, batchFlowBillEntity.getProductId())).collect(Collectors.toList());
                    List<ProductWarehouseEntity> productWarehouseEntityList = productWarehouseGroups.get(productId);
                    //获取涉及的仓库ID列表
                    List<Long> warehouseIdList = stockFlowBillEntityList.stream().map(StockFlowBillEntity::getWarehouseId).distinct().collect(Collectors.toList());
                    //处理每个分仓
                    for (Long warehouseId : warehouseIdList) {
                        //获取产品分仓数据
                        List<ProductWarehouseEntity> productWarehouseList = new ArrayList<>();
                        if (productWarehouseEntityList != null && !productWarehouseEntityList.isEmpty()) {
                            productWarehouseList = productWarehouseEntityList.stream().filter(productWarehouseEntity -> Objects.equals(warehouseId, productWarehouseEntity.getWarehouseId())).collect(Collectors.toList());
                        }
                        if (productWarehouseList.isEmpty()) {
                            continue;
                        }
                        List<StockFlowBillEntity> warehouseStockFlowBills = stockFlowBillEntityList.stream().filter(stockFlowBillEntity -> Objects.equals(warehouseId, stockFlowBillEntity.getWarehouseId())).sorted(Comparator.comparing(StockFlowBillEntity::getDate).thenComparing(StockFlowBillEntity::getId)).collect(Collectors.toList());
                        //判断该仓库是否存在流水数据
                        if (warehouseStockFlowBills == null || warehouseStockFlowBills.isEmpty()) {
                            continue;
                        }
                        List<BatchFlowBillEntity> warehouseBatchFlowBills = new ArrayList<>();
                        if (!batchFlowBillEntityList.isEmpty()) {
                            warehouseBatchFlowBills = batchFlowBillEntityList.stream().filter(batchFlowBillEntity -> Objects.equals(warehouseId, batchFlowBillEntity.getWarehouseId())).sorted(Comparator.comparing(BatchFlowBillEntity::getDate).thenComparing(BatchFlowBillEntity::getId)).collect(Collectors.toList());
                        }
                        //比较各种单据与流水数据变化是否一致
                        ProductEntityExt productEntityExt = productEntityMap.get(productId);
                        JSONObject productData=new JSONObject();
                        if (Objects.nonNull(productEntityExt.getData())){
                            productData = productEntityExt.getData();
                        }
                            //无批次
                            if (warehouseBatchFlowBills.isEmpty()) {
                                //调用重算方法-组装参数
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put(SelectProductEnum.PRODUCT.getAttr(), productId);
                                jsonObject.put(SelectProductEnum.WAREHOUSE.getAttr(), warehouseId);
                                jsonObject.put(SelectProductEnum.UNIT.getAttr(), productData.get(ProductEnum.UNIT.getAttr()));
                                jsonObject.put(ProductEnum.PARENT_ID.getSaasAttr(), productEntityExt.getParentId());
                                jsonObject.put(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr(), productData.get(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
                                jsonArray.add(jsonObject);
                            } else {
                                for (BatchFlowBillEntity batchFlowBillEntity : warehouseBatchFlowBills) {
                                    //调用重算方法-组装参数
                                    JSONObject jsonObject = new JSONObject();
                                    jsonObject.put(SelectProductEnum.PRODUCT.getAttr(), productId);
                                    jsonObject.put(SelectProductEnum.WAREHOUSE.getAttr(), warehouseId);
                                    jsonObject.put(SelectProductEnum.UNIT.getAttr(), productData.get(ProductEnum.UNIT.getAttr()));
                                    jsonObject.put(ProductEnum.PARENT_ID.getSaasAttr(), productEntityExt.getParentId());
                                    jsonObject.put(SelectProductEnum.EXPIRE_DATE.getAttr(), batchFlowBillEntity.getExpireDate());
                                    jsonObject.put(SelectProductEnum.PRODUCE_DATE.getAttr(), batchFlowBillEntity.getProduceDate());
                                    jsonObject.put(SelectProductEnum.GUARANTEE_PERIOD.getAttr(), batchFlowBillEntity.getGuaranteePeriod()/86400);
                                    jsonObject.put(SelectProductEnum.BATCH.getAttr(), batchFlowBillEntity.getBatch());
                                    jsonObject.put(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr(), productData.get(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
                                    jsonArray.add(jsonObject);
                                }
                            }
                    }
                }
                //调用统一的重算方法
                if (!jsonArray.isEmpty()) {
                    LOG.warn("重算产品数据："+jsonArray.toJSONString());
                    data.put(OutstockEnum.PRODUCT.getAttr(), jsonArray);
                    data.put(OutstockEnum.TIME.getAttr(), lastCheckOutdateStart);
                    CostRecalculationDTO costRecalculationDTO = new CostRecalculationDTO();
                    costRecalculationDTO.setType(StockTypeEnum.IN_STOCK.getCode());
                    costRecalculationDTO.setData(data);
                    costRecalculationDTO.setCorpid(corpid);
                    costRecalculationDTO.setMark(BasicConstant.THREE);
                    costRecalculationDTO.setIsWorkFlow(BasicConstant.ONE);
                    costRecalculationProducer.sendMessage(costRecalculationDTO);
                }
            }
        }
    }

    /**
     * 新增反结账
     *
     * @param settleAccountsDTO
     * @throws XbbException 业务异常
     * @author ruansicheng
     * @date 2021/11/19 2:13
     */
    @Override
    public SettleAccountsVO antiSettlement(SettleAccountsDTO settleAccountsDTO) throws XbbException {
        SettleAccountsVO settleAccountsVO = new SettleAccountsVO();
        String corpid = settleAccountsDTO.getCorpid();
        //结账中校验，在结账中不允许操作反结账
        String redisHelperValue = paasRedisHelper.getValue(RedisPrefixConstant.SETTLE_ACCOUNTS, corpid);
        if (StringUtil.isNotEmpty(redisHelperValue)) {
            throw new XbbException(SettleAccountErrorCodeEnum.API_ERROR_254007);
        }
        //获取最近上一次结账记录
        SettleAccountsEntity lastSettleAccounts = settleAccountsModel.getLastSettleAccounts(corpid);
        if (Objects.isNull(lastSettleAccounts)) {
            throw new XbbException(SettleAccountErrorCodeEnum.API_ERROR_254008);
        }
        //获取最近上一次结账记录时间
        Long lastCheckOutDate = lastSettleAccounts.getCheckOutTime();
        Long antiSettlementDate = settleAccountsDTO.getDate();
        //校验时间---不能超过6个月
        int month = DateTimeUtil.getMonthNum(lastCheckOutDate, DateUtil.getNow());
        if (month >= BasicConstant.LIMIT_ANTI_SETTLEMENT_DATE) {
            throw new XbbException(SettleAccountErrorCodeEnum.API_ERROR_254003);
        }
        String antiSettlementUserId = settleAccountsDTO.getUserId();
        String antiSettlementUserName = settleAccountsDTO.getLoginUserName();
        lastSettleAccounts.setAntiSettlementTime(antiSettlementDate);
        lastSettleAccounts.setAntiSettlement(BasicConstant.ONE);
        lastSettleAccounts.setAntiSettlementUserId(antiSettlementUserId);
        lastSettleAccounts.setAntiSettlementUserName(antiSettlementUserName);
        Integer flag = settleAccountsModel.update(lastSettleAccounts);
        if (flag < 1) {
            throw new XbbException(SettleAccountErrorCodeEnum.API_ERROR_254004);
        }
        //记录操作日志
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_ANTI_SETTLEMENT), antiSettlementUserName);
        mongoLogHelp.buildLog4InfoArrWithoutAsync(null, corpid, antiSettlementUserId, antiSettlementUserName, OperateModuleTypeEnum.ANTI_SETTLEMENT, OperateTypeEnum.NEW,
                "", "", memo, "");
        settleAccountsVO.setDataId(lastSettleAccounts.getId());
        return settleAccountsVO;
    }

    @Override
    public SettleAccountsListVO getSettleAccountsList(SettleAccountsListDTO settleAccountsListDTO) throws XbbException {
        SettleAccountsListVO settleAccountsListVO = new SettleAccountsListVO();
        String corpid = settleAccountsListDTO.getCorpid();
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID, corpid);
        params.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        params.put("antiSettlement", settleAccountsListDTO.getSettleAccountsType());
        if (Objects.equals(settleAccountsListDTO.getSettleAccountsType(), BasicConstant.ZERO)) {
            //按照结账时间倒排序
            String sortStr = "check_out_time DESC";
            params.put("orderByStr", sortStr);
        } else {
            //按照反结账时间倒排序
            String sortStr = "update_time DESC";
            params.put("orderByStr", sortStr);
        }
        //获取总数
        Integer entityCount = settleAccountsModel.getEntitysCount(params);
        Integer page = settleAccountsListDTO.getPage();
        Integer pageSize = settleAccountsListDTO.getPageSize();
        params.put("start", (long) (page - 1) * pageSize);
        params.put("pageNum", pageSize);
        List<SettleAccountsEntity> entities = settleAccountsModel.findEntitys(params);
        settleAccountsListVO.setSettleAccountsEntityList(entities);
        PageHelper pageHelper = new PageHelper(page, pageSize);
        pageHelper.setRowsCount(entityCount);
        settleAccountsListVO.setPageHelper(pageHelper);
        return settleAccountsListVO;
    }

}
